package com.authine.cloudpivot.ext.controller.FinancingScale;

import cn.hutool.core.lang.Assert;
import com.authine.cloudpivot.engine.api.model.organization.UserModel;
import com.authine.cloudpivot.engine.api.model.runtime.BizObjectCreatedModel;
import com.authine.cloudpivot.engine.api.model.runtime.WorkItemModel;
import com.authine.cloudpivot.engine.api.model.runtime.WorkflowInstanceModel;
import com.authine.cloudpivot.engine.enums.status.SequenceStatus;
import com.authine.cloudpivot.ext.Utils.CustomSchemaCode;
import com.authine.cloudpivot.ext.service.CloudSqlService;
import com.authine.cloudpivot.web.api.controller.base.BaseController;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

@RestController
@RequestMapping("/public/FinancingScaleUse")
@Slf4j
public class FinancingScaleUse extends BaseController {


    @Autowired
    CloudSqlService sqlService;

    /**
     *  融资  审批流完成后 数据写到-融资 基础
     */
    @RequestMapping("finish")
    public void finish(String bizId){
        BizObjectCreatedModel bizObject = getBizObjectFacade().getBizObject(CustomSchemaCode.FinancingScaleUse, bizId);

        List<Map<String,Object>> list = (List<Map<String, Object>>) bizObject.get("SheetFaScaleUse");

        String now = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

        //获取审批人
        String approval = "";
//        String approval = getFileBaseInfoWorkFlowApproval(bizObject);

        for (Map<String, Object> map : list) {
            String companyNumber = (String) map.get("companyNumber");
            String CASNumber = (String) map.get("CASNumber");
            Date openingDate = (Date) map.get("openingDate");

            if (openingDate.after(new Date())){

            }

            String format = DateFormatUtils.format(openingDate, "yyyy-MM-dd");
            String format1 = DateFormatUtils.format(openingDate, "yyyy-MM-dd");




            try {
                //获取数据
                Map<String, Object> data = fileInfoBaseMap(map, now, approval);
                //判断是否已存在
                String id = existsBizObject(map);
                if (StringUtils.isNotEmpty(id)) {
                    data.put("id", id);
                }

                BizObjectCreatedModel model = new BizObjectCreatedModel(CustomSchemaCode.FinancalScaleUseBase, data, false);
                model.setSequenceStatus(SequenceStatus.COMPLETED.name());
                id = getBizObjectFacade().saveBizObject(CustomSchemaCode.adminUserId, model, false);
                log.info("基础表-公司级档案操作成功 ");
                //调用存储过程
                callProcess(id);

            } catch (Exception e) {
                log.info("基础表-总公司档案操作失败 companyNumber={},CASNumber={}", companyNumber,CASNumber);
                log.info(e.getMessage(), e);
            }

        }
    }
    @RequestMapping("toVoid")
    public void toVoid(String bizId){
        BizObjectCreatedModel bizObject = getBizObjectFacade().getBizObject(CustomSchemaCode.FinancalScaleUseVoid, bizId);
        List<Map<String,Object>> list = (List<Map<String, Object>>) bizObject.get("SheetFaScaleUseVoid");

        String now = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

        //获取审批人
        String approval = "";
//        String approval = getFileBaseInfoWorkFlowApproval(bizObject);

        for (Map<String, Object> map : list) {
//            String oneLevelCode = (String) map.get("oneLevelCode");
//            String funCode = (String) map.get("funCode");

            try {
                //获取数据
                Map<String, Object> data = fileInfoBaseMap(map, now, approval);
                //判断是否已存在
                String id = existsBizObject(data);
                if (StringUtils.isNotEmpty(id)) {
                    data.put("id", id);
                }

                BizObjectCreatedModel model = new BizObjectCreatedModel(CustomSchemaCode.FinancalScaleUseBase, data, false);
                model.setSequenceStatus(SequenceStatus.CANCELED.name());
                id = getBizObjectFacade().saveBizObject(CustomSchemaCode.adminUserId, model, false);
                log.info("基础表-公司级档案作废操作成功 ");
                //调用存储过程
                callProcessToVoid(id);

            } catch (Exception e) {
//                log.info("基础表-总公司档案作废操作失败 oneLevelCode={},funCode={}", oneLevelCode,funCode);
//                log.info(e.getMessage(), e);
            }

        }
    }



    /**
     *  调用存储过程
     create   proc   [dbo].[FinancingUse]
     @CompanyFid   nvarchar(100),			----公司FID
     @ItemCode	  nvarchar(100),			----事项代码
     @Item		  nvarchar(100),			----代码
     @StartDate	  nvarchar(100),			----开启日
     @PlanEndDate   nvarchar(100),			----计划封闭日
     @EndDate		nvarchar(100),			----封闭日
     @SuppCode		nvarchar(100),			----往来单位代码
     @Scale			decimal(18,6),			----规模
     @FlowLoan		decimal(18,6),			----流贷
     @GuarLetter		decimal(18,6),		----保函
     @BankDraft		decimal(18,6),			----银票
     @Credit			decimal(18,6),		----信用证
     @Other			decimal(18,6),			----租赁
     @Desc			nvarchar(200),			----说明
     @Auditor	  nvarchar(50)				----审批人   02.0100 张三

     融资规模使用
      * @param bizId
     */
    private void callProcess(String bizId){

        if (StringUtils.isEmpty(bizId)) {
            return;
        }
        BigDecimal zero= BigDecimal.valueOf(0);
        //编写sql
        String tableName = getBizObjectFacade().getTableName(CustomSchemaCode.FinancalScaleUseBase);
        StringBuilder sql = new StringBuilder("SELECT RelevanceCompany,txtItemCode,itemName,openingDate,plannedClosingDate,closingDate,CASNumber,scale,currentLoan,guarantee,yinpiao,xinyongzheng,other,description,auditer from ")
                .append(tableName).append(" where id ='")
                .append(bizId).append("';");
        //查询到入参
        Map<String, Object> map = sqlService.getMap(sql.toString());

        log.info("入参map={}",map);

        //调用存储过程
        String RelevanceCompany = MapUtils.getString(map,"RelevanceCompany","");
        String ItemCode = MapUtils.getString(map,"txtItemCode","");//事项代码
        String ItemName  = MapUtils.getString(map,"itemName","");//事项

        LocalDateTime openingDateTemp = (LocalDateTime) map.get("openingDate");
        String openingDate =  ObjectUtils.isEmpty(openingDateTemp) ? "" : openingDateTemp.toLocalDate().toString();
        LocalDateTime plannedClosingDateTemp = (LocalDateTime) map.get("plannedClosingDate");
        String plannedClosingDate =  ObjectUtils.isEmpty(plannedClosingDateTemp) ? "" : plannedClosingDateTemp.toLocalDate().toString();
        LocalDateTime closingDateTemp = (LocalDateTime) map.get("closingDate");
        String closingDate =  ObjectUtils.isEmpty(closingDateTemp) ? "" : closingDateTemp.toLocalDate().toString();
//        DateFormatUtils.format(closingDateTemp,"yyyy-MM-dd");
//        Date closingDate = (Date) map.get("closingDate");
//        String closingDate = ObjectUtils.isEmpty(closingDate01) ? "is null" : "= '"+closingDate01.toString()+"'";

        String CASNumber = MapUtils.getString(map,"CASNumber","");

//        String scale = MapUtils.getString(map,"scale","");
//        BigDecimal scale = (BigDecimal)MapUtils.getNumber(map,"scale",0);
        double scale = ((BigDecimal)map.get("scale")).doubleValue();
//        bizObject.getData().get("exchangeRate");//获取主表数据 汇率
//        String currentLoan = MapUtils.getString(map,"currentLoan","");
//        String guarantee = MapUtils.getString(map,"guarantee","");
//        BigDecimal currentLoan = (BigDecimal)MapUtils.getNumber(map,"currentLoan",0);
        double currentLoan = ((BigDecimal)map.get("currentLoan")).doubleValue();
//        BigDecimal guarantee = (BigDecimal)MapUtils.getNumber(map,"guarantee",0);
        double guarantee = ((BigDecimal)map.get("guarantee")).doubleValue();
        double yinpiao = ((BigDecimal)map.get("yinpiao")).doubleValue();
        double xinyongzheng = ((BigDecimal)map.get("xinyongzheng")).doubleValue();
        double other = ((BigDecimal)map.get("other")).doubleValue();
//        (new BigDecimal("0E-8")).doubleValue()
//        String other = MapUtils.getString(map,"other","");
        String description = MapUtils.getString(map,"description","");

        String auditer = MapUtils.getString(map,"auditer","");



        String execSql = String.format("exec [HG_LINK].[hg].[dbo].FinancingUse '%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s'",
                RelevanceCompany,ItemCode,ItemName,openingDate,plannedClosingDate,closingDate,CASNumber,scale,currentLoan,guarantee,yinpiao,xinyongzheng,other,description,auditer );

        log.info("\n==========准备调用存储过程:{}",execSql);

        sqlService.execute(CloudSqlService.htEas,execSql);

        log.info("\n=============存储过程执行完成");

    }

    /**
     *  调用作废存储过程
     融资规模作废
     exec   [dbo].[FinancingUseVoid]		-----融资规模使用作废    公司+事项号+往来单位代码  确定唯一性
     @CompanyFid   nvarchar(100),			----公司FID
     @ItemCode	  nvarchar(100),			----事项代码
     @SuppCode		nvarchar(100),			----往来单位代码
     @Auditor	  nvarchar(50)				----审批人   02.0100 张三

      * @param bizId
     */
    private void callProcessToVoid(String bizId){

        if (StringUtils.isEmpty(bizId)) {
            return;
        }
        //编写sql
        String tableName = getBizObjectFacade().getTableName(CustomSchemaCode.FinancalScaleUseBase);
        StringBuilder sql = new StringBuilder("SELECT RelevanceCompany,txtItemCode,CASNumber,auditer from  ")
                .append(tableName).append(" where id ='")
                .append(bizId).append("';");
        //查询到入参
        Map<String, Object> map = sqlService.getMap(sql.toString());

        log.info("入参map={}",map);

        //调用存储过程

        String RelevanceCompany = MapUtils.getString(map,"RelevanceCompany","");
//        Date openingDateObj = (Date) map.get("openingDate");
//        String openingDate = DateFormatUtils.format(openingDateObj,"yyyy-MM-dd");
        String ItemCode = MapUtils.getString(map,"txtItemCode","");
        String CASNumber = MapUtils.getString(map,"CASNumber","");
        String auditer = MapUtils.getString(map,"auditer","");




        String execSql = String.format("exec [HG_LINK].[hg].[dbo].FinancingUseVoid '%s','%s','%s','%s'",
                RelevanceCompany,ItemCode,CASNumber,auditer );

        log.info("\n==========准备调用作废存储过程:{}",execSql);

        sqlService.execute(CloudSqlService.htEas,execSql);

        log.info("\n=============作废存储过程执行完成");

    }

    /**
     *  查询审批人,返回  员工号+姓名
     * @param bizObject
     * @return
     */
    private String getFileBaseInfoWorkFlowApproval(BizObjectCreatedModel bizObject) {


        WorkflowInstanceModel instanceModel = getWorkflowInstanceFacade().getByObjectId(bizObject.getId());
        List<WorkItemModel> workItems = getWorkflowInstanceFacade().getWorkItems(instanceModel.getId(), true);
        final String finalActivityCode = "Activity14";
        Optional<WorkItemModel> first = workItems.stream().filter(a -> a.getActivityCode().equals(finalActivityCode)).findFirst();
        String participant = null;
        if (first.isPresent()) {
            WorkItemModel workItemModel = first.get();
            participant = workItemModel.getParticipant();
        }

        if (participant == null) {
            participant = bizObject.getCreater().getId();
        }

        UserModel user = getOrganizationFacade().getUser(participant);


        return new StringBuilder(user.getEmployeeNo()).append(" ").append(user.getName()).toString();
    }



    /**
     * 判断是否已存在
     * @return
     */
    private String existsBizObject(Map data){

        String tableName = getBizObjectFacade().getTableName(CustomSchemaCode.FinancalScaleUseBase);
        String companyNumber = (String) data.get("companyNumber");//公司
        String CASNumber = (String) data.get("CASNumber");//往来单位代码
        String ItemNumber = (String) data.get("txtItemCode");//事项号
        Date openingDateTemp = (Date) data.get("openingDate");
        String openingDate = DateFormatUtils.format(openingDateTemp, "yyyy-MM-dd");


        StringBuilder sql = new StringBuilder("select id  from ").append(tableName)
                .append(" where companyNumber='").append(companyNumber).append("' and CASNumber='")
                .append(CASNumber).append("' and txtItemCode='")
                .append(ItemNumber).append("';");

        Map<String, Object> map = sqlService.getMap(sql.toString());

        return (String) map.get("id");
    }

    /**
     *  转换成  基础表-融资 的数据
     * @param map
     * @param auditDate
     * @return
     */
    private Map<String,Object> fileInfoBaseMap(Map<String,Object> map,String auditDate,String auditer){
        Map<String, Object> data = new HashMap<>();

        //公司
        data.put("RelevanceCompany",map.get("RelevanceCompany"));
        //公司代码
        data.put("companyNumber",map.get("companyNumber"));
        //公司名称
        data.put("companyNumber",map.get("companyNumber"));
        //财务部门
        data.put("RelevanceFADept",map.get("RelevanceFADept"));
        //财务部门代码
        data.put("FADeptNumber",map.get("FADeptNumber"));

        //事项代码
        data.put("txtItemCode",map.get("txtItemCode"));
        //事项
        data.put("itemName",map.get("ShortText1691740462276"));


        //开启日
        data.put("openingDate",map.get("openingDate"));
        //计划封闭日
        data.put("plannedClosingDate",map.get("plannedClosingDate"));
        //封闭日
        data.put("closingDate",map.get("closingDate"));
        //往来单位代码
        data.put("CASNumber",map.get("CASNumber"));

        //简称
        data.put("CASSimplename",map.get("CASSimplename"));
        //管理部门代码
        data.put("manageDeptNumber",map.get("manageDeptNumber"));
        //管理部门
        data.put("manageDeptName",map.get("manageDeptName"));
        //岗A代码
        data.put("posANumber",map.get("posANumber"));

        //岗A
        data.put("posAName",map.get("posAName"));
        //岗B代码
        data.put("posBNumber",map.get("posBNumber"));
        //岗B
        data.put("posBName",map.get("posBName"));
        //规模
        data.put("scale",map.get("Number1691994052750"));

        //流贷
        data.put("currentLoan",map.get("NumbercurrentLoan"));
        //保函
        data.put("guarantee",map.get("Numberguarantee"));
        //其他
        data.put("other",map.get("NumberOther"));
        //说明
        data.put("description",map.get("description"));
        //银票
        data.put("yinpiao",map.get("Numberyinpiao"));
        //信用证
        data.put("xinyongzheng",map.get("Numberxinyongzheng"));

        //审批时间
        data.put("auditDate",auditDate);
        //审批人
        data.put("auditer",auditer);

        return data;
    }
}
